package com.handpay.zztong.hp.smartpay.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.handpay.framework.ClientEngine;
import com.handpay.framework.MD5;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.notification.model.MerchantInfo;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.smartpay.SignUtil;
import com.handpay.zztong.hp.utils.AccountUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;


/**
 * 智能还款
 */
public class IntrePaymentHtmlActivity extends ZZTongActivity implements OnClickListener {
    /**
     * 加载网页的webview
     */
    public WebView webView;
    /**
     * 网页加载的地址
     */


    private MyWebViewClient webViewClient;
    private ProgressBar progressBar;
    private ImageView btnfunction;
    public static final String ShowHtml_Html_Path_Key = "ShowHtml_Html_Path_Key";
    public static final String ShowHtml_Html_DES_Key = "ShowHtml_Html_DES_Key";
    private String des3Key ;
    private String host ;

    @Override
    protected boolean isShownTabs() {
        return false;
    }

    @Override
    protected boolean isShownTopBar() {
        return false;
    }

    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(this.getString(R.string.tv_loan_title), true);
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setContentView(R.layout.activity_show_html);
        super.onCreate(savedInstanceState);
        webView = (WebView) findViewById(R.id.userServiceWebView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        btnfunction = (ImageView) findViewById(R.id.btn_goToFunction);
        btnfunction.setImageBitmap(null);
        btnfunction.setBackgroundResource(R.drawable.dialog_market_exit_btn);
        btnfunction.setOnClickListener(this);
        btnfunction.setVisibility(View.INVISIBLE);
        //获取商户信息并且加载网页
        getMerchantInfo();
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient());
        webViewClient = new MyWebViewClient();
        webView.setWebViewClient(webViewClient);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        host = getIntent().getStringExtra(ShowHtml_Html_Path_Key);
        des3Key = getIntent().getStringExtra(ShowHtml_Html_DES_Key);
    }

    class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("closewindow")) {
                finish();
            } else {
                view.loadUrl(url);
            }
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (progressBar != null)
                progressBar.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_goToFunction) {
            goBack();
        }
    }




    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert) {
        if (super.netJsonResponse(action, resp, showAlert)) return true;
        if (action.equals(ZZTongActivity.DO_zztGetMerchantInfo)) {
            MerchantInfo merchInfo = (MerchantInfo) resp;
            String name = SecureManager.getInstance().des(merchInfo.getName(), 0, null);
            String bankName = SecureManager.getInstance().des(merchInfo.getBankName(), 0, null);
            String cardNum = SecureManager.getInstance().des(merchInfo.getCardNum(), 0, null);
            String mSubBankName = SecureManager.getInstance().des(merchInfo.getSubBranchName(), 0, null);
            String certNo = SecureManager.getInstance().des(merchInfo.getCertNo(), 0, null);
            String mSubBankCode = merchInfo.getSubBankCode();//服务器未加密
            merchInfo.setName(name);
            merchInfo.setBankName(bankName);
            merchInfo.setCardNum(cardNum);
            merchInfo.setSubBranchName(mSubBankName);
            merchInfo.setSubBankCode(mSubBankCode);
            AccountUtils.saveUserName(this, name);
            AccountUtils.setAccountStatus(this, AccountUtils.convertStatus(merchInfo.getStatus()));
            String phone = SecureManager.getInstance().des(merchInfo.getPhone(), 0, null);
            AccountUtils.setAccountPhone(this, phone);
            AccountUtils.saveUsercertNo(this, certNo);
            String url = getSmartPayUrl(AccountUtils.getUserName(this), AccountUtils.getAccountPhone(this), AccountUtils.getUsercertNo(this), ClientEngine.CHANNEL,AccountUtils.getMerchantCode(this));
            webView.loadUrl(url);
        }
        return false;
    }

    /**
     * 智能还款
     *
     * @param userName
     * @param phoneNo
     * @param certNo
     * @throws Exception
     */
    public  String getSmartPayUrl(String userName, String phoneNo, String certNo, String chinnel,String merchantCode) {

        Map<String, String> params = new HashMap<>();
        String realName = null;// 需要URLEncoder.encode
        try {
            realName = java.net.URLEncoder.encode(userName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String phone = SecureManager.getInstance().des(phoneNo, 1, des3Key);// 需要指定AES加密
        String idCode = SecureManager.getInstance().des(certNo, 1, des3Key);// 需要指定AES加密
        String openid = null;// 非必传
        String channelCode = chinnel;//
        String merAgentCode = "10001";//
        params.put(BaseProtocolKey.REAL_NAME, realName);// encode
        params.put(BaseProtocolKey.PHONE, phone);// 3DES加密
        params.put(BaseProtocolKey.ID_CODE, idCode);// 3DES加密
        params.put(BaseProtocolKey.CHANNEL_CODE, channelCode);
        params.put(BaseProtocolKey.MER_AGENT_CODE, merAgentCode);
        String sign = SignUtil.getSignVeryfy(params, des3Key);
        StringBuilder url = new StringBuilder(host);
        url.append("?" + BaseProtocolKey.REAL_NAME + "=" + realName);
        url.append("&" + BaseProtocolKey.PHONE + "=" + phone);
        url.append("&" + BaseProtocolKey.ID_CODE + "=" + idCode);
        url.append("&" + BaseProtocolKey.CHANNEL_CODE + "=" + channelCode);
        url.append("&" + BaseProtocolKey.MER_AGENT_CODE + "=" + merAgentCode);
        url.append("&" + BaseProtocolKey.OPENID + "=" + openid);
        url.append("&" + BaseProtocolKey.MERCHANTCODE + "=" + SecureManager.getInstance().des(merchantCode, 1, des3Key));
        url.append("&" + BaseProtocolKey.SIGN + "=" + sign);
        HPLog.i("url", url);
        return url.toString();
    }


    private void showError() {
        showAlertDialog(this, getString(R.string.tip), "数据加载异常，请重新尝试！", false, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                goBack();
                dialog.dismiss();
            }
        });
    }

    private void getMerchantInfo() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(BaseProtocolKey.NEWBANKFLAG, ZZTongActivity.newBankFlag);
        doJsonPost(this, ZZTongActivity.DO_zztGetMerchantInfo, MerchantInfo.class, params);

    }
}
